import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:hand_writing/database/database.dart';
import 'package:provider/provider.dart';

import '../../uril/color.dart';
import '../../uril/date.dart';
import 'index_state.dart';
import 'index_view.dart';

class IndexProvider extends ChangeNotifier {
  final AppDatabase database;
  final state = IndexState(notes: []);

  IndexProvider(this.database) {
    initNotes();
  }

  Future<void> initNotes() async {
    state.notes = [];
    notifyListeners();

    await Future.delayed(const Duration(milliseconds: 10));
    final result = await database.getAllNotesOrderByDate();

    state.notes = result.cast<Note>();
    notifyListeners();
  }


  changeStr(String val) {
    state.note = Note(
      id: state.note?.id ?? 0,
      content: val,
      createdAt: state.note?.createdAt ?? DateTime(2000, 1, 1),
    );
    notifyListeners();
  }

  saveNote(BuildContext context) async {
    print(state.note?.content);
    if (state.note!.content.length > 0) {
      if (state.note!.id == 0) {
        await database.addNote(state.note!.content);
        Navigator.pop(context);
        Fluttertoast.showToast(
          msg: '保存成功',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.black54,
          textColor: Colors.white,
          fontSize: 16.0,
        );
        await initNotes();
      } else {
        await database.updateNoteContent(state.note!.id, state.note!.content);
        Navigator.pop(context);
        Fluttertoast.showToast(
          msg: '更新成功',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          timeInSecForIosWeb: 1,
          backgroundColor: Colors.black54,
          textColor: Colors.white,
          fontSize: 16.0,
        );
        await initNotes();
      }

    }
  }

  delete(int id) async {
    await database.deleteNoteById(id);
    initNotes();
    Fluttertoast.showToast(
      msg: '删除成功',
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.BOTTOM,
      timeInSecForIosWeb: 1,
      backgroundColor: Colors.black54,
      textColor: Colors.white,
      fontSize: 16.0,
    );
  }

  showEdit(BuildContext context, Note note) {
    if (note.id != 0) {
      state.note = note;
    } else {
      state.note = Note(id: 0, content: '', createdAt: DateTime(2000, 1, 1));
    }
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),

      builder: (context) {
        return SafeArea(child: NoteEditorSheet());
      },
    );
  }
}
